<?php

class DeleteImageAction extends CAction
{
    public function run()
    {
        if(!Yii::app()->request->isPostRequest || !isset($_GET['step']) || !isset($_GET['recipeId']))
            throw new CHttpException(400,'the request is invalid');

        $step=Step::loadObjectById($_GET['step'],array('image'));
        if($step===null)
            throw new CHttpException(404,'The requested step does not exist.');
        if($step->recipeId!=$_GET['recipeId'])
            throw new CHttpException(403,'cannot edit the step not belong to the recipe');
        if($step->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the step not belong to you');

        $recipe=Recipe::loadObjectById($_GET['recipeId'],array('steps'));
        if($recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if(array_search($_GET['step'], $recipe->steps)===false)
            throw new CHttpException(404,'The requested step does not belong to the recipe.');

        $succ=false;            
        if(!$step->image){
            $succ=true;
        }
        else {        
            $image = $step->image;
            $step->image = UserImage::$null;
            if(Step::saveObject($step, array('image'))) {
                UserImage::delete('step',$image);
                Recipe::saveObject($recipe,array('updateTime'));
                $succ=true;
            }
        }

        $this->controller->renderPartial('deleteImage',array('succ'=>$succ, 'step'=>$step, 'recipe'=>$recipe), false, true);
    }
}
  
?>
